define([
  'jquery',
  'jqueryui',
  'underscore',
  'backbone',
  'models/search/SearchModel',
  'text!templates/search/searchTemplate.html',
  'views/search/SearchResultsView',
  'msgbox',
], function($,ui, _, Backbone, SearchModel, searchTemplate,SearchResultsView,MsgBox){

  var SearchView = Backbone.View.extend({
    el: $(".mainpanel"),
    model: new SearchModel(),
    events: {'click #submitSearch' : 'submit',
        "change #searchForm :input" :"changedSearchForm"/*,
        "autocompleteselect": "changedSearchAC"*/} ,
    initialize: function(){
//    	_.bindAll("#searchForm :input", "changedSearchForm");
        var Hospitals = Backbone.Collection.extend({
            model: Backbone.Model.extend({url:'/allHospitals'}),
            url:'/allHospitals'
          });	
        this.allHospitals = new Hospitals();

    },
    render: function(){
		// this.model = new SearchModel(); 
    	var self=this;
    	
        var renderApp = _.after(1, function(){
        	console.log(self);
        	var data = {
          		  search: self.model,
          		  allHospitals:self.allHospitals.models,
          	        _: _ 
          	      };
      	      var compiledTemplate = _.template( searchTemplate, data );
      	      self.$el.html(compiledTemplate);
    	  	    $(".searchhospital").multiselect({
    	  	    	noneSelectedText: "Labs",
    	  	    	multiple: false,
      	  		   selectedList: 1
      	    	}).multiselectfilter();

      	      $("input#followupdoctorname").autocomplete({
      	    	    source: function(request,response){
      	    			 $.ajax({
      	    			        type: "GET",
      	    			        url: "/getExistingDoctors",
      	    			        success: function(data){
      	    			              response($.map(data, function(item) {
      	    			                    return { 
      	    			                        label: item,
      	    			                        value: item
      	    			                        };
      	    			                    }));
      	    			        }
      	    		    });
      	    	    },
      	    	    minLength: 0,
      	    	    select: function(e,ui){
      	    	    	self.changedSearchAC("followupdoctorname",ui);
      	    	    }
      	    	}).focus(function () {
      	    	    $(this).autocomplete("search");
      	    	});

      	      
      	      $("input#complaint").autocomplete({
      	    	    source: "/getKeyword",
      	    	    minLength: 2,
      	    	    select: function(e,ui){
      	    	    	self.changedSearchAC("complaint",ui);
      	    	    }
      	    	});
      	      
      	      $("input#doctorname").autocomplete({
      	    	    source: function(request,response){
      	    			 $.ajax({
      	    			        type: "GET",
      	    			        url: "/getDoctorName?speciality="+$("#speciality").val()+"&term="+$("#doctorname").val(),
      	    			        success: function(data){
      	    			              response($.map(data, function(item) {
      	    			                    return { 
      	    			                        label: item.doctor.name,
      	    			                        value: item.doctor.name
      	    			                        };
      	    			                    }));
      	    			        }
      	    		    });
      	    	    },
      	    	    minLength: 3,
      	    	    select: function(e,ui){
      	    	    	self.changedSearchAC("doctorname",ui);
      	    	    }
      	    	});
      	      
      	      $("input#speciality").autocomplete({
      	    	    source: function(request,response){
      	    			 $.ajax({
      	    			        type: "GET",
      	    			        url: "/getSpeciality?keyword="+$("#complaint").val()+"&term="+$("#speciality").val(),
      	    			        success: function(data){
      	    			              response($.map(data, function(item) {
      	    			                    return { 
      	    			                        label: item.speciality +" - "+item.description.substring(0,60)+"..",
      	    			                        value: item.speciality
      	    			                        };
      	    			                    }));
      	    			        }
      	    		    });
      	    	    },
      	    	    minLength: 0,
      	    	    select: function(e,ui){
      	    	    	self.changedSearchAC("speciality",ui);
      	    	    }
      	    	}).focus(function () {
      	    	    $(this).autocomplete("search");
      	    	});
      	      $( "#datepicker" ).datepicker();
        });
    	this.allHospitals.fetch({success: renderApp});

    },
    close: function(){
    	
    },
    submit: function(){
    	if($.isEmptyObject(this.model.toJSON()) && $(".searchhospital").val()==0){
	      		 $.msgBox({
					    title:"Appment",
					    content:"Please fill-in at least 1 search criteria",
					    type:"error"
					});

    	}else{
    		var queryString="";
        	_.each(this.model.toJSON(), function(value, key) {
        	    queryString=queryString+key+'='+value+'&';
        	  }); 
        	queryString = queryString+"hospital="+$(".searchhospital").val();
        	var self=this;
	   		 $.ajax({
			        type: "POST",
			        url: "/getSearchResults?"+queryString,
			        success: function(data){
			        	self.model.set("searchresults",data);
			        	//data = _(data).flatten(true);
			        	self.goTo("searchresults");
			        }
		    });

//    		this.model.fetch({data: JSON.stringify(this.model)});	
    	}
    },
    changedSearchAC: function ( e, ui ) {
        var value = $("#"+e).val();
        var obj = "{\""+e +"\":\""+ui.item.value+"\"}";
        var objInst = JSON.parse(obj);
        this.model.set(objInst);
    	
  
    },
    changedSearchForm:function(evt) {
       var changed = evt.currentTarget;
       var value = $("#"+changed.id).val();
       var obj = "{\""+changed.id +"\":\""+value+"\"}";
       var objInst = JSON.parse(obj);
       this.model.set(objInst);
    }
  });

  return SearchView;
});
